const { Service } = require('egg')
const cheerio = require('cheerio')

module.exports = class SinfoService extends Service {
  /**
   * * 学籍卡片信息
   * @return {Object} *
   */
  async table() {
    const Cookie = this.ctx.state.Cookie
    const { sid } = this.ctx.data
    const info = {}
    try {
      /* 在教务主页中获取个人信息的链接 */
      const mainUrl = `${this.ctx.state.baseUrl}/xs_main.aspx?xh=${sid}&zgh=${sid}`
      const mainDom = await this.ctx.curl(mainUrl, {
        method: 'GET',
        headers: {
          Cookie,
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
          Host: this.ctx.state.baseUrl.replace('https://', ''),
        },
        timeout: 10000,
        rejectUnauthorized: false, // 忽略证书验证
      })
      const dom$ = cheerio.load(mainDom.data.toString())
      const apiUrl = encodeURI(`${this.ctx.state.baseUrl}/${dom$('a:contains("个人信息")').first().attr('href')}`)
      // console.log('apiUrl', apiUrl)
      /* end */

      const res = await this.ctx.curl(apiUrl, {
        method: 'GET',
        headers: {
          Cookie,
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
          Host: this.ctx.state.baseUrl.replace('https://', ''),
          Referer: mainUrl,
        },
        timeout: 5000,
        rejectUnauthorized: false, // 忽略证书验证
      })
      // console.log('res.status', res.status);
      if (res.status === 200) {
        const pageXml = res.data.toString()
        const $ = cheerio.load(pageXml)
        // 拿到数据存于数组dataList
        const dataList = [
          $('#lbl_xy').text().replace(/\s/g, ''),
          $('#lbl_zymc').text().replace(/\s/g, ''),
          $('#lbl_xz').text().replace(/\s/g, ''),
          $('#lbl_xzb').text().replace(/\s/g, ''),
          $('#xh').text().replace(/\s/g, ''),
          $('#xm').text().replace(/\s/g, ''),
          $('#lbl_xb').text().replace(/\s/g, ''),
          $('#lbl_dqszj').text().replace(/\s/g, ''),
        ]
        const tableList = ['院系', '专业', '学制', '班级', '学号', '姓名', '性别', '年级']
        // 键值对处理
        const result = {}
        tableList.forEach((key, i) => { result[key] = dataList[i] })
        return result
      }
      return info
    } catch (err) {
      console.log('err', err)
      throw err
    }
  }
}
